<template>
  <draggable group="default" v-model="data.list" item-key="name" @add="receiveAdd" style="height: 100%">
    <template #item="{ element, index }">
      <div class="little-bear-draggable-item little-bear-drag-item" data-draggable="true">
        <div :class="['little-bear-drag-tool', { active: dragFormSelect.key === element.key }]" @click.stop="dragFormHandleSelect(element)">
          <div class="little-bear-drag-mask"></div>
          <div class="little-bear-drag-l">
            <!--拖拽-->
            <div class="little-bear-drag-btn" style="cursor: move">
              <my-icon class="fc-icon" name="el-icon-Rank" size="14" />
            </div>
          </div>
          <div class="little-bear-drag-r">
            <!-- 复制 -->
            <div class="little-bear-drag-btn" @click="dragFormHandleCopy()">
              <my-icon class="fc-icon" name="el-icon-CopyDocument" size="14" />
            </div>
            <!-- 删除 -->
            <div class="little-bear-drag-btn little-bear-drag-danger" @click="dragFormHandleDlete(index)">
              <my-icon class="fc-icon" name="el-icon-DeleteFilled" size="14" />
            </div>
          </div>
          <el-col :span="24" class="fc-form-col">
            <component v-if="elementComponent" :is="elementComponent" :value="element.options.defaultValue" :element="element"></component>
          </el-col>
        </div>
      </div>
    </template>
  </draggable>
</template>

<script setup>
import draggable from 'vuedraggable';
import { useDragStore } from '@/store/modules/drag';
import { loadComponent, components } from '@/elements/index';

// 接收父节传入点参数
const props = defineProps({
  key: String, // 唯一标识
  element: Object, // 元素数据
});

// 选择拖动表单-选择组件信息
let dragFormSelect = reactive({
  key: '',
});

const dragStore = useDragStore();

// 组件key
let key = ref('');

// 组件
let elementComponent = ref(null);

/**
 * 接收父节点传入的参数
 * @param obj 父节点传入的参数
 */
const receiveAdd = (obj) => {
  elementComponent.value = loadComponent(dragStore.data.list[obj.newDraggableIndex].type);
  dragStore.data.list[obj.newDraggableIndex].component = loadComponent(dragStore.data.list[obj.newDraggableIndex].type);
  dragStore.data.select = dragStore.data.list[obj.newDraggableIndex];
};

/**
 * 选择拖动表单-选择组件
 * @param element 组件对象数据
 */
const dragFormHandleSelect = (element) => {
  key.value = element.key;
};

/**
 * 选择拖动表单-删除
 * @param index 组件对象数组下标
 */
const dragFormHandleDlete = async (index) => {
  dragStore.data.list.splice(index, 1);
  key.value = '';
};

/**
 * 计算属性
 */
const data = computed(() => dragStore.data);
</script>
